package com.hxzy.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.bean.User;
import com.hxzy.service.UserService;
import com.hxzy.service.impl.UserServiceImpl;
import com.hxzy.vo.JsonResult;
import com.hxzy.vo.StatusCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author nick
 */
@WebServlet("/validateAccount")
public class ValidateAccountServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        //从request中获取传递的用户名
        String account = req.getParameter("account");
        if (!Objects.nonNull(account)){
            JsonResult jsonResult = new JsonResult();
            jsonResult.setCode(StatusCode.UNKNOWN_ERROR.getCode());
            jsonResult.setMessage(StatusCode.UNKNOWN_ERROR.getMessage());
            JsonResult.write2client(jsonResult, resp);
            return;
        } else {
            //调用业务逻辑层查看用户是否存在
            UserService service = new UserServiceImpl();
            User user = service.findByAccount(account);//根据账户查询用户信息

            JSONObject jsonObject = new JSONObject();//当做map用
            /*
            * user不为null，说明account账户已经被注册
            * user为null，说明account没有被注册
            * */
            jsonObject.put("valid", user == null);

            JsonResult.write2client(jsonObject, resp);
            return;
        }
    }
}
